package com.wyj.utils

import android.view.View
import androidx.annotation.Nullable
import com.google.gson.Gson
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import org.json.JSONObject
import java.io.File
import java.util.concurrent.TimeUnit

object Utils {

    @JvmStatic
    fun isNullOrEmpty(str: String?): Boolean {
        return str == null || str.isNullOrBlank()
    }


    @JvmStatic
    fun isNullOrEmpty(list: Array<String>?): Boolean {
        return list == null || list.isEmpty()
    }

    @JvmStatic
    fun isNullOrEmpty(list: Collection<*>?): Boolean {
        return list == null || list.isEmpty()
    }

    @JvmStatic
    fun post(run: Runnable) {
        Observable.just(run).observeOn(AndroidSchedulers.mainThread()).subscribe { it.run() }
    }

    @JvmStatic
    fun postDelay(run: Runnable, delay: Long) {
        Observable.timer(delay, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread()).subscribe {
            run.run()
        }
    }

    @JvmStatic
    inline fun <reified T> clone(e: T): T {
        val gson = Gson()
        return gson.fromJson(gson.toJson(e), T::class.java)
    }

    @JvmStatic
    fun getByCollection(list: List<String>, index: Int): String {
        return if (index >= 0 && index < list.size) list[index] else ""
    }

    @JvmStatic
    fun <T> getByCollection(list: List<T>, index: Int, default: T): T {
        return if (index >= 0 && index < list.size) list[index] else default
    }


    @JvmStatic
    fun length(list: Collection<*>?): Int {
        return list?.size ?: 0
    }

    @JvmStatic
    fun isFile(str: String?): Boolean {
        return try {
            if (isNullOrEmpty(str)) false else File(str).isFile
        } catch (e: Exception) {
            false
        }
    }

    @JvmStatic
    fun getStr(str1: String?, str2: String): String {
        return if (com.wyj.utils.isNullOrEmpty(str1)) str2 else str1
    }

    @JvmStatic
    fun getViewWidthAndHeight(view: View): IntArray {
        val width = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        val height = View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
        view.measure(width, height)
        return intArrayOf(view.measuredWidth, view.measuredHeight)
    }
}